package cn.com.customer.manager.ui.login

import android.annotation.SuppressLint
import cn.com.customer.manager.application.App
import cn.com.customer.manager.bean.User
import cn.com.customer.manager.http.BaseApi.IAuthorization
import cn.com.customer.manager.http.subscriber.TipRequestSubscriber
import cn.com.customer.manager.manager.LoginManager
import cn.com.customer.manager.manager.TokenManager
import com.xuexiang.xhttp2.XHttpProxy
import com.xuexiang.xhttp2.annotation.ThreadType
import com.xuexiang.xhttp2.exception.ApiException


class AccountLoginPresenter constructor(view: AccountLoginContract.View) : AccountLoginContract.Presenter {
    private val mView = view

    init {
        mView.setPresenter(this)
    }

    /**
     * 开始
     */
    override fun start() {
    }

    /**
     * 账号密码登录
     * @param phone 用户手机号码
     * @param pass 用户密码
     */
    @SuppressLint("CheckResult")
    override fun login(phone: String, pass: String) {
        XHttpProxy.proxy(IAuthorization::class.java, ThreadType.TO_IO)
                .login(phone, pass)
                .flatMap {
                    var token = ""
                    it?.let {
                        token = it.token
                        TokenManager.getInstance()
                                .setToken(token)
                    }

                    return@flatMap XHttpProxy.proxy(IAuthorization::class.java, ThreadType.TO_IO).userInfo(token)
                }
                .subscribeWith(object : TipRequestSubscriber<User>() {
                    override fun onSuccess(t: User?) {
                        t?.let {
                            LoginManager.getInstance(App.getContext()).saveUser(it)
                            mView.loginSuccess()
                        }
                    }
                    override fun onError(e: ApiException?) {
                        super.onError(e)
                    }
                }
                )
    }
}


